<!--导出excel-->
<template>
  <el-drawer
    :title="'导出:' + fileName + '/' + sheetName"
    :visible.sync="drawerVisible"
    size="400px"
    :show-close="!exporting"
    :before-close="evtClose"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    :with-header="true"
    :append-to-body="true"
  >
    <div style="padding: 10px; height: 100%; overflow-y: auto">
      <el-card shadow="hover" style="margin-bottom: 10px">
        <div style="color: #666; font-weight: bold; margin-bottom: 10px">
          导出哪些列？
        </div>
        <div style="color: #666; margin-bottom: 20px">
          <el-checkbox-group v-model="checkeds">
            <el-checkbox
              v-for="item in columns"
              :label="item.prop"
              style="font-size: 12px; font-weight: normal; margin: 6px 10px"
              :key="item.prop"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </el-card>
      <el-card shadow="hover" style>
        <div style="color: #666; font-weight: bold; margin-bottom: 10px">
          导出文件名称
        </div>
        <div style="color: #666; margin-bottom: 20px">
          <el-input v-model="inputFileName" placeholder="请输入导出文件名称">
            <template slot="append">.xlsx</template>
          </el-input>
        </div>
      </el-card>
      <div
        style="
          width: 100%;
          margin-top: 20px;
          margin-bottom: 40px;
          text-align: center;
        "
      >
        <div v-show="exporting" v-text="exportingMsg"></div>
        <el-progress
          :text-inside="true"
          v-show="exporting"
          :stroke-width="26"
          :percentage="exportPercentage"
        ></el-progress>
        <el-button
          type="primary"
          style="width: 160px; margin-top: 20px"
          @click="exportSubmit"
          v-show="!exporting"
          :disabled="this.rows === 0"
          >导出数据</el-button
        >
      </div>
    </div>
  </el-drawer>
</template>
<script>
import XLSX from "xlsx";
export default {
  name: "exporExcel",
  data() {
    return {
      drawerVisible: false,
      checkeds: [],
      exporData: [],
      inputFileName: this.fileName,
      inputSheetName: this.sheetName,
      exportPercentage: 0,
      exporting: false,
      exportingMsg: "正在获取数据",
      fields: "code,name",
      searchObj: {},
    };
  },
  props: {
    fileName: {
      type: String,
      default: "默认导出数据",
    },
    sheetName: {
      type: String,
      default: "默认导出数据",
    },
    rows: {
      type: Number,
      default: 0,
    },
    type: null,
    columns: null,
    query: null,
    exportApi: null,
  },
  methods: {
    //来自父组件调用
    exportOpen() {
      let that = this;
      that.checkeds = [];
      this.columns.forEach(function (item) {
        if (item.prop == "sexName") {
          item.prop = "sex";
        }
        that.checkeds.push(item.prop);
      });
      this.drawerVisible = true;
    },
    evtClose(done) {
      done(!this.exporting);
    },
    async exportSubmit() {
      let that = this;
      //获取字段
      if (that.checkeds.length === 0) {
        that.$message.error("请选择要需要导入字段项目");
        return;
      }
      console.log(that.checkeds);

      that.exportPercentage = 0;
      that.fields = that.checkeds.join(",");
      that.exporting = true;
      let pageSize = 50;
      let page = {};
      that.exporData = [];
      let headerTitle = {};

      that.checkeds.forEach(function (item) {
        headerTitle[item] = that.columns.filter(
          (col) => col.prop === item
        )[0].label;
      });
      that.exporData.push(headerTitle);
      let pages = Math.ceil(this.rows / pageSize);

      that.exportingMsg = "正在获取数据";
      for (let i = 1; i <= pages; i++) {
        page = { pageSize: pageSize, pageIndex: i };
        let res = await this.funLoadData(pageSize, i);
        var lostListData = res.data.rows;
        console.log(lostListData);
        lostListData.forEach((val) => {
          if (val.sex) {
            val.sex = val.sex == "0" ? "女" : "男";
          }
        });
        that.exportPercentage = parseInt((i / pages) * 100);
        that.exporData = this.exporData.concat(res.data.rows);
      }
      that.exportingMsg = "正在写文件";
      setTimeout(function () {
        const header = { header: that.checkeds, skipHeader: true };
        const ws = XLSX.utils.json_to_sheet(that.exporData, header);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, that.sheetName);
        XLSX.writeFile(wb, that.inputFileName + ".xlsx");
        that.exporting = false;
        that.drawerVisible = false;
        this.checkeds = [];
      }, 100);
    },
    funLoadData(pageSize, i) {
      if (this.type != "自定义") {
        let that = this;
        let page = {
          pageIndex: i,
          pageSize: pageSize,
        };
        return new Promise((resolve, reject) => {
          that
            .exportApi(
              JSON.stringify(page),
              JSON.stringify(that.query),
              that.fields,
              this.query.tableOrder,
              this.query.sort
            )
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        });
      } else {
        let that = this;
        return new Promise((resolve, reject) => {
          that
            .exportApi({
              ...that.searchObj,
              pageIndex: i,
              pageSize,
              fields: that.fields,
            })
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        });
      }
    },
  },
  created() {},
};
</script>


